<?php

namespace App\Http\Controllers\Mp;

use App\Http\Requests\Mp\EditChildren;
use App\Http\Requests\Mp\StoreChildren;
use App\Http\Resources\Mp\ChildrenResource;
use App\Models\Child;
use App\Services\ChildService;
use Illuminate\Support\Facades\DB;

/**
 * Class ChildController
 * @package App\Http\Controllers\Mp
 * 子女卡管理
 */
class ChildController extends BaseController
{
    /**
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     * 子女卡列表
     */
    public function index()
    {
        $children = Child::query()
            ->orderBy('created_at', 'desc')
            ->withCount('orders')
            ->where('user_id', \Auth::id())->get();
        return ChildrenResource::collection($children);
    }

    /**
     * @param StoreChildren $request
     * @param ChildService $childService
     * @return ChildrenResource|array
     * @throws \Exception
     * 添加子女卡 - 自动订餐
     */
    public function store(StoreChildren $request, ChildService $childService)
    {
        DB::beginTransaction();
        try {
            $child = new Child();
            $child->fill($request->all());
            $child->user_id = \Auth::id();
            $child->save();
            $child = $childService->autoOrder($request, $child);
            DB::commit();
            return new ChildrenResource($child);
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->fail($exception->getMessage());
        }
    }

    /**
     * @param $id
     * @return ChildrenResource|array
     * 展示子女卡
     */
    public function show($id)
    {
        $child = Child::query()->where('user_id', \Auth::id())->find($id);
        if (!$child) return $this->fail('该子女卡不存在');
        return new ChildrenResource($child);
    }

    /**
     * @param EditChildren $request
     * @param $id
     * @param ChildService $childService
     * @return ChildrenResource|array
     * @throws \Exception
     * 修改子女卡 - 自动订餐
     */
    public function update(EditChildren $request, $id, ChildService $childService)
    {
        DB::beginTransaction();
        try {
            $child = Child::where('user_id', \Auth::id())->find($id);
            if (!$child) throw new \Exception('该子女卡不存在');
            $child->fill($request->all());
            $child->save();
            $child = $childService->autoOrder($request, $child);
            DB::commit();
            return new ChildrenResource($child);
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->fail($exception->getMessage());
        }
    }
}
